/**
 * Created by liyun on 2015/10/27.
 */
var fs = require("fs");
var debug = require('debug')('routes:material');
require('date-utils');
var Material = require('../models/material');
var Sim = require('../models/sim');
var config=require('../config');
var qiniu = require('qiniu');
var BoxBuyer = require('../models/box_buyer');

qiniu.conf.ACCESS_KEY = config.ACCESS_KEY;
qiniu.conf.SECRET_KEY = config.SECRET_KEY;

var uptoken = new qiniu.rs.PutPolicy(config.Bucket_Name);



module.exports = function (app) {

    app.get('/material/list', list);
    app.post('/material/add',add);
    app.get('/material/add',goAddPage);
    app.post('/material/updateSim',updateSim);
    app.get('/uptoken', uptokenfn);
    app.post('/downtoken', downtoken);
    app.post('/material/remove', remove);

};

function downtoken(req, res) {

    var key = req.body.key,
        domain = req.body.domain;

    //trim 'http://'
    if (domain.indexOf('http://') != -1) {
        domain = domain.substr(7);
    }
    //trim 'https://'
    if (domain.indexOf('https://') != -1) {
        domain = domain.substr(8);
    }
    //trim '/' if the domain's last char is '/'
    if (domain.lastIndexOf('/') === domain.length - 1) {
        domain = domain.substr(0, domain.length - 1);
    }

    var baseUrl = qiniu.rs.makeBaseUrl(domain, key);
    var deadline = 3600 + Math.floor(Date.now() / 1000);

    baseUrl += '?e=' + deadline;
    var signature = qiniu.util.hmacSha1(baseUrl, config.SECRET_KEY);
    var encodedSign = qiniu.util.base64ToUrlSafe(signature);
    var downloadToken = config.ACCESS_KEY + ':' + encodedSign;

    if (downloadToken) {
        res.json({
            downtoken: downloadToken,
            url: baseUrl + '&token=' + downloadToken
        })
    }
}

function uptokenfn(req, res, next) {
    var token = uptoken.token();
    res.header("Cache-Control", "max-age=0, private, must-revalidate");
    res.header("Pragma", "no-cache");
    res.header("Expires", 0);
    if (token) {
        res.json({
            uptoken: token
        });
    }
}

function remove(req,res){
    /*var client = new qiniu.rs.Client();
    client.remove(config.Bucket_Name, req.params.key, function(err, ret) {
        if (!err) {
            res.send({msg:true});
        } else {
            res.send({msg:false});
            console.log(err);
            // http://developer.qiniu.com/docs/v6/api/reference/codes.html
        }
    })*/

    /*var path0 = new qiniu.rs.EntryPath(config.Bucket_Name, key0);
    var path1 = new qiniu.rs.EntryPath(bucketName, key1);
    var path2 = new qiniu.rs.EntryPath(bucketName, key2);*/
    var client = new qiniu.rs.Client();
    var path = new Array();
    var imgs = req.body.imgs.split(',');
    imgs.forEach(function(imgurl){
        path.push(new qiniu.rs.EntryPath(config.Bucket_Name, imgurl));
    });

    client.batchDelete(path, function(err, ret) {
        if (!err) {
            for (var i in ret) {
                if (ret[i].code !== 200) {
                    console.log(ret[i].code, ret[i].data);
                }
            }
            new Material().updateMaterialByUserId(req.session.user._id,{$pullAll:{imgs:imgs}},function(err){
                if(err){
                    res.send({msg:false});
                }else{
                    res.send({msg:true});
                }
            });
        } else {
            res.send({msg:false});
        }
    });

}

//广告列表
function list(req,res){
    var userid = req.session.user._id;
    if(req.session.user.user!='admin'){
        var buyer_id=req.session.user.buyer_id;
        new BoxBuyer().findIdsByBuyer(buyer_id,function(datas) {
            new Sim().findUserSimById({box_id: datas[0].box_id},function(err,doc) {
                imgsAndSims(res, doc, userid);
            });
        });
    }else{
        new Sim().findAll(function(sims){
            imgsAndSims(res, sims, userid);
        });

    }
}

function imgsAndSims(res, sims, userid){

        new Material().findMaterialById(userid, function(arr){
            imgs=null;
            debug('~~~~~~~~~~~~~~~~~~~~');
            debug(arr);
            if(arr){
                imgs = arr.imgs;
                debug('~~~~~~~~~~~~~~~~~~~~');
                debug(arr);
                debug('~~~~~~~~~~~~~~~~~~~~');
            }
            res.render('material/list',{
                arr:imgs,
                sims:sims,
                domain:config.Domain
            });
        });

}

function goAddPage(req,res){
    res.render('material/add_material', {
        domain: config.Domain,
        uptoken_url: config.Uptoken_Url
    });
}

function add(req,res){
    var userid = req.session.user._id;
    var imgs = req.body.imgs.split(';');
    imgs = imgs.slice(1,imgs.length);
    var material = new Material({userid:userid,imgs:imgs});
    material.findMaterialById(userid,function(arr){
        if(arr){
            material.updateMaterialByUserId(userid,{$push:{imgs:{$each:imgs}}},function(err){
                res.redirect('material/list');
            });
        }else{
            material.save(function(err){
                res.redirect('material/list');
            });
        }
    });

}

function updateSim(req,res){
    var imgs = req.body.imgs.split(',');
    var sims = req.body.sims.split(',');

    new Sim().updateSims(sims,imgs,function(err){
        res.send({msg:true});
    });


    /*new Sim({userid:userid,imgs:imgs}).save(function(err){
        res.redirect('material/list');
    })*/
}

